package com.oa.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.joneying.common.annotation.CommonService;
import com.joneying.common.web.response.Resp;
import com.oa.admin.dto.SealAddDTO;
import com.oa.admin.dto.SealUpdateDTO;
import com.oa.admin.entity.SealKeepingRecords;
import com.oa.admin.service.ISealKeepingRecordsService;
import com.oa.admin.vo.SealDetailsVO;
import com.oa.admin.vo.SealKeepingRecordsListVO;
import com.oa.admin.vo.SealListVO;
import com.oa.core.PageResult;
import com.oa.admin.entity.Seal;
import com.oa.admin.mapper.SealMapper;
import com.oa.admin.service.ISealService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.oa.core.constant.Constant;
import com.oa.core.exception.BusinessException;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.pm.service.IOrganizationService;
import com.oa.system.entity.User;
import com.oa.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 公章表 服务实现类
 * </p>
 *
 * @author syb123
 * @since 2019-01-22
 */
@Service
public class SealServiceImpl extends ServiceImpl<SealMapper, Seal> implements ISealService {

    private final SealMapper sealMapper;
    private final ISealKeepingRecordsService sealKeepingRecordsService;
    private final IUserService userService;
    private final IOrganizationService organizationService;

    @Autowired
    public SealServiceImpl(SealMapper sealMapper, ISealKeepingRecordsService sealKeepingRecordsService, IUserService userService, IOrganizationService organizationService) {
        this.sealMapper = sealMapper;
        this.sealKeepingRecordsService = sealKeepingRecordsService;
        this.userService = userService;
        this.organizationService = organizationService;
    }

    @Override
    @CommonService
    public PageResult<Seal> findList(Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            List<Seal> list = sealMapper.findList();
            return new PageResult<>(list);
        } else {
            // 当前页，总条数 构造 page 对象
            Page<Seal> page = new Page<>(pageNum, pageSize);
            //查询
            List<Seal> list = sealMapper.findList(page);
            return new PageResult<>(list);
        }
    }

    /**
     * 根据id查询
     */
    @Override
    @CommonService
    public Seal findSealById(String id) {
        return sealMapper.findById(id);
    }

    /**
     * 添加公章
     *
     * @param sealAddDTO
     * @return
     */
    @Override
    @CommonService
    @Transactional
    public Resp addSeal(String userId, SealAddDTO sealAddDTO) throws BusinessException {
        User user = userService.selectById(userId);
        Seal seal = new Seal();
        BeanUtils.copyProperties(sealAddDTO, seal);

        try {
            seal.setCustodian(user.getName());
            sealMapper.insert(seal);

            SealKeepingRecords sealKeepingRecords = new SealKeepingRecords();
            sealKeepingRecords.setSealId(seal.getId());
            sealKeepingRecords.setKeeper(user.getId());
            sealKeepingRecords.setKeepingDepartment(organizationService.selectById(user.getDepartmentId()).getId());
            sealKeepingRecords.setTime(new Date());
            sealKeepingRecordsService.insert(sealKeepingRecords);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("添加公章失败!");
        }

        return new Resp<String>().success("添加公章成功");
    }

    /**
     * 修改公章
     *
     * @param sealUpdateDTO
     * @return
     */
    @Override
    @CommonService
    @Transactional
    public Resp updateSeal(SealUpdateDTO sealUpdateDTO) throws BusinessException {

        Seal sealOld = sealMapper.findById(sealUpdateDTO.getId());


        //判断是否修改了保管人
        if (!StringUtils.isEmpty(sealUpdateDTO.getCustodian())) {
            if (!sealOld.getCustodian().equals(sealUpdateDTO.getCustodian())) {
                SealKeepingRecords sealKeepingRecords = new SealKeepingRecords();
                sealKeepingRecords.setSealId(sealOld.getId());
                sealKeepingRecords.setTime(new Date());
                //记录
                User user = userService.selectById(sealOld.getCustodian());
                sealKeepingRecords.setKeeper(user.getName());
                sealKeepingRecords.setKeepingDepartment(organizationService.findOrganizationById(user.getDepartmentId()).getOrganizationName());
                sealKeepingRecordsService.insert(sealKeepingRecords);
            }
        }

        Seal seal = new Seal();

        BeanUtils.copyProperties(sealUpdateDTO, seal);

        try {
            sealMapper.updateById(seal);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("修改公章失败!");
        }


        return new Resp<String>().success("修改公章成功");
    }

    /**
     * 根据主键id删除公章
     *
     * @param id
     * @return
     */
    @Override
    @CommonService
    @Transactional
    public Resp deleteSeal(String id) throws BusinessException {

        Seal seal = sealMapper.findById(id);
        seal.setIsDeleted(1);

        try {
            seal.updateById();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("删除公章失败!");
        }

        List<SealKeepingRecords> sealKeepingRecords = sealKeepingRecordsService.selectList(new EntityWrapper<SealKeepingRecords>().eq("is_deleted", Constant.IS_DELETE_NO).eq("seal_id", seal.getId()));
        if (CollUtil.isNotEmpty(sealKeepingRecords)) {
            sealKeepingRecords.forEach(x -> {
                x.setIsDeleted(1);
                sealKeepingRecordsService.updateById(x);
            });
        }

        return new Resp<String>().success("删除公章成功");
    }

    /**
     * 查询公章列表
     *
     * @param
     * @param
     * @return
     */
    @Override
    @CommonService
    public PageResult<SealListVO> findSealList(Integer pageNum, Integer pageSize) throws DataIsEmptyException {
        if (pageNum == null) {
            List<SealListVO> list = sealMapper.findSealList();
            if (CollUtil.isEmpty(list)) {
                throw new DataIsEmptyException();
            }
            return new PageResult<SealListVO>(list);
        } else {
            Page<SealListVO> page = new Page<>(pageNum, pageSize);
            List<SealListVO> list = sealMapper.findSealList(page);
            if (CollUtil.isEmpty(list)) {
                throw new DataIsEmptyException();
            }
            return new PageResult<SealListVO>(list);
        }
    }

    /**
     * 根据主键id查询公章详情
     *
     * @param id
     * @return
     */
    @Override
    @CommonService
    public Resp findSealDetailsById(String id) throws DataIsEmptyException {
        SealDetailsVO sealDetailsVO = sealMapper.findSealDetailsById(id);
        if (StringUtils.isEmpty(sealDetailsVO)) {
            throw new DataIsEmptyException();
        }
        List<SealKeepingRecordsListVO> sealKeepingRecords = sealKeepingRecordsService.findSealKeepingRecordsList(id);
        sealDetailsVO.setSealKeepingRecords(sealKeepingRecords);
        return new Resp<SealDetailsVO>().success(sealDetailsVO);
    }
}
